<?php

declare(strict_types=1);
/**
 * Created by project.
 * User: huanzipap
 * Date: 2023/5/10
 * Time: 11:25
 */
namespace App\Libs;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;

class Upload
{
    #[Inject] protected RequestInterface $request;
    #[Inject] protected ResponseInterface $response;

    protected string $upload_path;

    /**
     * 上传图片|文件
     * @param int $back_format
     * @return object|array
     */
    public function uploadFile(int $back_format=1): object|array
    {
        if($this->request->hasFile('file')){
            $file = $this->request->file('file');
            if($file->isValid()) {
                $extension = $file->getExtension();
                if (!in_array(strtolower($extension), [
                    'jpg','jpeg','png','pptx','xlsx','word','docx','pdf','txt','mp3','mp4'
                ])) {
                    return $this->response->json(['code'=>0,'message'=>'格式只允许jpg|jpeg|png|pptx|xlsx|word|docx|pdf|txt|mp3|mp4']);
                }
                //获取原文件全称
                $fileNameFull = $file->getClientFilename();

                //过滤特殊字符
                $toReplace = ['，', '|'];
                $replaceWith = '';
                $fileNameFull = str_replace($toReplace,$replaceWith,$fileNameFull);

                //切割分解文件名称
                $fileNameArr = explode('.',$fileNameFull);
                $fileCount = count($fileNameArr);
                //原文件名
                $originalFileName = $fileNameArr[$fileCount-2].'.'.$fileNameArr[$fileCount-1];
                //新文件名
                $newFilename = md5(date('YmdHis',time()).rand(1,999999)).'.'.$fileNameArr[$fileCount-1];

                //获取上传参数
                $file_dir = $this->request->input('file_dir',null);
                $file_type = $this->request->input('file_type',null);

                //项目环境信息
                $this->upload_path = config('upload')['path'];
                $app_name = config('app_name');
                $app_env = config('app_env');

                //项目默认为uploads（暂不支持更改）
                $defaultDir = 'uploads';

                //文件详细目录
                $fileDescPath = $defaultDir;
                if($file_dir) $fileDescPath .= '/'.$file_dir;
                if($file_type) $fileDescPath .= '/'.$file_type;
                $fileDescPath .= '/'.date('Ymd',time());


                //上传文件保存路径
                $savePath = $this->upload_path;
                if($app_env) $savePath .= '/'.$app_env;
                $savePath .= '/'.$fileDescPath;

                var_dump($savePath);
                //保存路径不存在就创建
                if(!file_exists($savePath)){
                    self::createDir($savePath);
                }
                $savePath .= '/'.$newFilename;

                //访问目录
                $webPath = $fileDescPath.'/'.$newFilename;
                //因为中文问题需要给路径加上中文名称
                $webPathTitle = $webPath.'|'.$originalFileName;

                //上传
                $upValid = move_uploaded_file($file->getRealPath(),$savePath);
                if ($upValid) {
                    $backData['ext'] = $extension;
                    $backData['name'] = $originalFileName;
                    $backData['path'] = $webPath;
                    $backData['path_title'] = $webPathTitle;
                    if($back_format==2){
                        return $backData;
                    }
                    return $this->response->json(['code' => 1, 'message' => 'success','data'=>$backData]);
                }else{
                    return $this->response->json(['code' => 0, 'message' => '文件上传出错']);
                }
            }else{
                return $this->response->json(['code' => 0, 'message' => '文件验证出错']);
            }
        }else{
            return $this->response->json(['code' => 0, 'message' => '文件丢失']);
        }
    }


    /**
     * 功能：循环检测并创建文件夹
     * @param $path
     * @return null
     */
    static function createDir($path){
        if (!file_exists($path)){
            static::createDir(dirname($path));
            mkdir($path, 0777); //检查是否有该文件夹，如果没有就创建，并给予最高权限
        }
    }




    /**
     * 上传图片
     * @param int $back_format
     * @return object|array
     */
    public function uploadImage(int $back_format=1):object|array
    {
        if($this->request->hasFile('file')){
            $file = $this->request->file('file');

            if($file->isValid()) {
                $extension = $file->getExtension();
                if (!in_array(strtolower($extension), ['jpg','jpeg','png'])) {
                    return $this->response->json(['code' => 0,'message' => '图片格式只允许jpg,jpeg,png']);
                }

                //获取原文件名称
                $fileName = $file->getClientFilename();
                $fileNameArr = explode('.',$fileName);
                //新文件名
                $newFilename = $fileNameArr[0].'-'.date('His',time()).'.'.$fileNameArr[1];

                //获取上传参数
                $file_dir = $this->request->input('file_dir',null);
                $file_type = $this->request->input('file_type','image');//默认image

                //环境信息
                $app_name = config('app_name');
                $app_env = config('app_env');

                //文件详细目录
                $fileDescPath = '/uploads';
                if($file_dir) $fileDescPath .= '/'.$file_dir;
                if($file_type) $fileDescPath .= '/'.$file_type;
                $fileDescPath .= '/'.date('Ymd',time());

                //保存路径
                $savePath = '/data/project/static';
                if($app_env) $savePath .= '/'.$app_env;
                $savePath .= $fileDescPath;
                //保存路径不存在就创建
                if(!file_exists($savePath)){
                    self::createDir($savePath);
                }
                $savePath .= '/'.$newFilename;

                //访问目录
                $app_name ? $webPath = $app_name.'/static' : $webPath = 'static';
                if($app_env) $webPath .= '/'.$app_env;
                $webPath .= $fileDescPath.'/'.$newFilename;

                //上传
                $upValid = move_uploaded_file($file->getRealPath(),$savePath);
                if ($upValid) {
                    $backData['ext'] = $extension;
                    $backData['name'] = $newFilename;
                    $backData['path'] = $webPath;
                    if($back_format==2){
                        return $backData;
                    }
                    return $this->response->json(['code' => 1, 'message' => 'success','data'=>$backData]);
                }else{
                    return $this->response->json(['code' => 0, 'message' => '文件上传出错']);
                }
            }else{
                return $this->response->json(['code' => 0, 'message' => '文件验证出错']);
            }
        }else{
            return $this->response->json(['code' => 0, 'message' => '文件丢失']);
        }

    }

}